package com.yanwq.sayhi.controller.article.activity;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yanwq.sayhi.R;
import com.yanwq.sayhi.base.BaseToolbarActivity;
import com.yanwq.sayhi.common.client.OkJsonObjectResponseCallback;
import com.yanwq.sayhi.common.client.OkRequestParams;
import com.yanwq.sayhi.common.client.OkRestClient;
import com.yanwq.sayhi.common.constant.CacheConstant;
import com.yanwq.sayhi.common.constant.RegexConstant;
import com.yanwq.sayhi.common.event.ArticleEvent;
import com.yanwq.sayhi.common.tool.SharedPrefTool;
import com.yanwq.sayhi.controller.audio.AudioRecorderWrap;
import com.yanwq.sayhi.controller.user.UserMgr;
import com.yanwq.sayhi.dao.bean.Article;
import com.yanwq.sayhi.dao.bean.Club;
import com.yanwq.sayhi.widget.MToast;

import java.io.File;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTouch;
import de.greenrobot.event.EventBus;

public class AudioAddActivity extends BaseToolbarActivity {
    private AudioRecorderWrap mRecorder;

    @BindView(R.id.audio_summary)
    EditText mSummaryV;
    @BindView(R.id.audio_record)
    TextView mTVRecord;
    @BindView(R.id.audio_pb)
    ProgressBar mPb;

    @OnClick(R.id.audio_record)
    public void record() {
        if (mTVRecord.getText().equals("我有话说")) {
            mTVRecord.setText("我说完了");
            mTVRecord.setTextColor(getResources().getColor(R.color.blue));
            mPb.setVisibility(View.VISIBLE);
            mRecorder.record();
        } else {
            mTVRecord.setText("我有话说");
            mTVRecord.setTextColor(getResources().getColor(R.color.gray));
            mPb.setVisibility(View.INVISIBLE);
            mRecorder.stop();
        }
    }

    private File mAudioFile;
    private String mFileUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio_add);
    }

    @Override
    public void init() {
        String mFileName = String.format("%s.amr", CacheConstant.getRandomFileName());
        mAudioFile = new File(CacheConstant.getAudioPath(), mFileName);
        mRecorder = new AudioRecorderWrap(new File(CacheConstant.getAudioPath(), mFileName));
    }

    @Override
    public void initView() {
        mToolbar.setTitle("发语音");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_send, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        send();
        return true;
    }

    private void send() {
        if (!Pattern.matches(RegexConstant.summary, mSummaryV.getText().toString())) {
            MToast.showShort(AudioAddActivity.this, "告诉大家你发的是什么~");
            return;
        }

        if (!mAudioFile.exists()) {
            MToast.showShort(AudioAddActivity.this, "你还没有说话~");
            return;
        }
        if (mFileUrl == null) {
            uploadAudio();
        } else {
            sendAudio();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mRecorder.release();
    }

    public void uploadAudio() {
        OkRequestParams params = new OkRequestParams();
        params.put("mf", mAudioFile);

        OkRestClient.getInstance().post(this, "/oss/file", params, new OkJsonObjectResponseCallback() {
            @Override
            public void onStart() {
                showProgressDialog("正在上传语音");
            }

            @Override
            public void onSuccess(JSONObject jsonObject) {
                mFileUrl = jsonObject.getString("fileUrl");
                sendAudio();
            }

            @Override
            public void onFail(int status, String s, Throwable throwable) {
                super.onFail(status, s, throwable);
                cancelProgressDialog();
            }

            @Override
            public void onStop() {
                cancelProgressDialog();
            }
        });
    }

    public void sendAudio() {
        Article article = new Article();
        article.setSummary(mSummaryV.getText().toString());
        article.setAudioUrl(mFileUrl);
        article.setLon(0);
        article.setLat(0);
        article.setType(2);
        article.setPermission(0);

        article.setUser(UserMgr.get());

        String path = "/article/add";

        if (SharedPrefTool.getConfig("mode", "").equals("club")) {
            Club club = new Club();
            club.setId(SharedPrefTool.getConfig("clubId", 0));
            article.setClub(club);
            path = "/article/add/club";
        }

        OkRestClient.getInstance().post(this, path, article,
                new OkJsonObjectResponseCallback() {
                    @Override
                    public void onStart() {
                        showProgressDialog("正在发布");
                    }

                    @Override
                    public void onSuccess(JSONObject jsonObject) {
                        Article article = JSON.parseObject(jsonObject.toJSONString(),
                                Article.class);
                        MToast.showShort(AudioAddActivity.this,
                                String.format("%s 发布成功", article.getSummary()));
                        delayFinish();

                        EventBus.getDefault().post(new ArticleEvent(
                                ArticleEvent.SEND_SUCCESS));
                    }

                    @Override
                    public void onStop() {
                        cancelProgressDialog();
                    }
                });
    }
}
